package com.lenovo.smarttraffic.ui.activity.stage3;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.bean.WeatherBean;
import com.lenovo.smarttraffic.database.SensorDataDB;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.ui.adapter.MyVpAdapter;
import com.lenovo.smarttraffic.ui.fragment.stage3.LifeHelperFragment;
import com.lenovo.smarttraffic.util.HttpUtils;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class LifeHelperActivity extends BaseActivity {

    private TextView temp_tv, temp2_tv;
    private View refresh;
    private LineChart lineChart;

    private RecyclerView life_rv;

    private ViewPager weather_vp;

    private Gson gson = new Gson();

    private Handler handler = new Handler();

    private List<Fragment> fragments = new ArrayList<>();

    private LinearLayout index;

    @Override
    protected int getLayout() {
        return R.layout.activity_life_helper;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar(this, "生活助手");

        temp_tv = findViewById(R.id.temp_tv);
        temp2_tv = findViewById(R.id.temp2_tv);
        refresh = findViewById(R.id.refresh);
        lineChart = findViewById(R.id.temp_chart);

        life_rv = findViewById(R.id.life_rv);
        weather_vp = findViewById(R.id.weather_vp);
        index = findViewById(R.id.index);

        refresh();
        initData();


        fragments.add(new LifeHelperFragment().setType(0));
        fragments.add(new LifeHelperFragment().setType(1));
        fragments.add(new LifeHelperFragment().setType(2));
        fragments.add(new LifeHelperFragment().setType(3));
        weather_vp.setAdapter(new MyVpAdapter(getSupportFragmentManager(), fragments));
        showTableText(0);
        weather_vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                showTableText(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        weather_vp.setOffscreenPageLimit(fragments.size());
    }

    private void showTableText(int index) {
        this.index.removeAllViews();
        for (int i = 0; i < fragments.size(); i++) {
            TextView textView = new TextView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textView.setPadding(10, 10, 10, 10);
            textView.setLayoutParams(layoutParams);
            switch (i) {
                case 0:
                    textView.setText("空气质量");
                    break;
                case 1:
                    textView.setText("温度");
                    break;
                case 2:
                    textView.setText("相对湿度");
                    break;
                case 3:
                    textView.setText("二氧化碳");
                    break;
            }
            textView.setBackground(getDrawable(R.color.White));
            if (i == index) {
                textView.setTextColor(Color.WHITE);
                textView.setBackground(getDrawable(R.color.Blue));
            }
            int finalI = i;
            textView.setOnClickListener(v -> weather_vp.setCurrentItem(finalI));
            this.index.addView(textView);
        }
    }


    public void initData() {
        refresh.setOnClickListener(v -> refresh2());
    }

    public void refresh() {
        HttpUtils.post("get_weather", new HttpUtils().setParam("UserName", MainActivity.userName), response -> {
            WeatherBean weatherBean = gson.fromJson(response.toString(), WeatherBean.class);
            if (weatherBean.getROWS_DETAIL() != null) {
                temp_tv.setText(weatherBean.getWCurrent() + "℃");
                temp2_tv.setText("今天：" + weatherBean.getROWS_DETAIL().get(0).getTemperature().replace("~", "-") + "℃");


                lineChart.clear();
                ArrayList<Entry> entryHight = new ArrayList<>();
                ArrayList<Entry> entryDown = new ArrayList<>();

                for (int i = 0; i < weatherBean.getROWS_DETAIL().size(); i++) {
                    WeatherBean.ROWSDETAILBean rowsdetailBean = weatherBean.getROWS_DETAIL().get(i);
                    String[] split = rowsdetailBean.getTemperature().split("~");
                    entryDown.add(new Entry(i, Integer.valueOf(split[0])));
                    entryHight.add(new Entry(i, Integer.valueOf(split[1])));
                }


                LineDataSet lineDataHight = new LineDataSet(entryHight, "最高温度");
                LineDataSet lineDataDown = new LineDataSet(entryDown, "最低温度");

                lineDataDown.setColor(Color.BLUE);
                lineDataHight.setColor(Color.RED);

                lineDataDown.setValueTextColor(Color.BLUE);
                lineDataHight.setValueTextColor(Color.RED);

                lineDataDown.setValueTextSize(8);
                lineDataHight.setValueTextSize(8);

                lineDataDown.setCircleRadius(1);
                lineDataHight.setCircleRadius(1);

                ArrayList<ILineDataSet> dataSets = new ArrayList<>();
                dataSets.add(lineDataHight);
                dataSets.add(lineDataDown);

                LineData lineData = new LineData(dataSets);
                XAxis xAxis = lineChart.getXAxis();
                xAxis.setDrawGridLines(false);

                xAxis.setValueFormatter((value, axis) -> {
                    switch ((int) value) {
                        case 0:
                            return "昨天";
                        case 1:
                            return "今天";
                        case 2:
                            return "明天";
                        case 3:
                            return "后天";
                        case 4:
                            return "星期四";
                        case 5:
                            return "星期五";
                        case 6:
                            return "星期六";
                    }
                    return "数据错误";
                });

                xAxis.setDrawAxisLine(false);
                xAxis.setTextColor(Color.BLUE);

                Description description = new Description();
                description.setText("");
                lineChart.setDescription(description);
                YAxis y = lineChart.getAxisRight();

                y.setDrawAxisLine(false);
                y.setTextSize(10);
                y.setTextColor(Color.GRAY);

                lineChart.setDoubleTapToZoomEnabled(false);
                lineChart.setHighlightPerTapEnabled(false);
                lineChart.setHighlightPerDragEnabled(false);
                lineChart.getAxisLeft().setEnabled(false);
                lineChart.setData(lineData);
                lineChart.invalidate();

                runnable.run();
                refresh2();
            }
        });
    }

    public void refresh2() {
        handler.postDelayed(() -> {
            runnable.run();
            refresh2();
        }, 3000);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            life_rv.setAdapter(new LifeRvAdapter(LitePal.order("date desc").find(SensorDataDB.class)));
        }
    };


}
